using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Text;
using System.Web;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Common;
using Sedna.Core.Controller.Configurations;

namespace Sedna.Core.Controls.Actions
{
    public class LoadEnumValuesAction: AbstractAction
    {
        private Type enumType;
        private IDataTranslator enum2textTranslator;
        private IDataTranslator enum2valueTranslator;
        private bool convertToString = true;
        private string dataSourcePath;

        #region Properties

        public Type EnumType
        {
            set { enumType = value; }
        }

        public IDataTranslator Enum2textTranslator
        {
            set { enum2textTranslator = value; }
        }

        public IDataTranslator Enum2valueTranslator
        {
            set { enum2valueTranslator = value; }
        }

        public bool ConvertToString
        {
            set { convertToString = value; }
        }

        public string DataSourcePath
        {
            set { dataSourcePath = value; }
        }

        #endregion

        public override IActionResult Execute(IExecutionContext executionContext)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Value", typeof(string));
            dt.Columns.Add("Text", typeof(string));
            
            Array values = System.Enum.GetValues(enumType);
            foreach (object enumValue in values)
            {
                object text = enum2textTranslator != null ? enum2textTranslator.Translate(null, enumValue) : enumValue;
                object value = enum2valueTranslator != null ? enum2valueTranslator.Translate(null, enumValue) : enumValue;
                if (convertToString)
                {
                    dt.Rows.Add(value!=null ? value.ToString():String.Empty, text != null ? text.ToString() : String.Empty);
                }
                else
                {
                    dt.Rows.Add(value, text);
                }
            }
            executionContext.SetPropertyValue(dataSourcePath, dt);
            return CreateResult();
        }
    }
}
